//
//  JDConfirmOrderViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/5/10.
//

import UIKit
import SwiftyJSON

/// 结算  确认订单页面
class JDConfirmOrderViewController: JDBaseViewController {

    var selectedShopCartModel: JDShopCartModel?
    var preOrderModel: JDPreOrderModel? 
    
    var bottomToolBarView: UIView?
    var mainTableView: UITableView?
    
    var settlementPriceLabel: UILabel?
    
    var currentCell: JDSettlementTableViewCell?
    
    var shopperName: String?
    var shopperIDCard: String?
    var shopperMsg: String?
    
    let payingVC = JDPayingViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupConfig()
        self.setupUIElements()
        self.setupBottomToolBarView()
//        self.createPreOrder()
        // Do any additional setup after loading the view.
        
        NotificationCenter.default.addObserver(self, selector: #selector(payResult(_:)), name: NSNotification.Name("payResult"), object: nil)
    }
    
    @objc func payResult(_ notify: NSNotification) {
        print("处理支付结果111")
        self.payingVC.dismiss(animated: false)
        
        let payResultType = notify.object as? String
        if payResultType == "成功" {
            let resultVC = JDPayResultViewController()
            resultVC.paySuccess = true
            self.hidesBottomBarPushViewController(resultVC)
            
        } else if payResultType == "失败" {
            let resultVC = JDPayResultViewController()
            resultVC.paySuccess = false
            self.hidesBottomBarPushViewController(resultVC)
            
        } else if payResultType == "取消" {
            let resultVC = JDPayResultViewController()
            resultVC.paySuccess = false
            resultVC.payResultStr = "用户取消支付"
            self.hidesBottomBarPushViewController(resultVC)
        }
        
        print("处理结果吧")
        
    }
    
    func setupConfig() {
        self.setupNavigationTitle("结算")
        self.setupLeftBackItem()
    }
    
    func setupUIElements() {
        
        self.bottomToolBarView = UIView()
        self.view.addSubview(self.bottomToolBarView!)
        self.bottomToolBarView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(76)//+38)
        })
        self.bottomToolBarView?.backgroundColor = .white
        
        // 此页面 使用tableview进行布局  走单cell进行拉布局
        self.mainTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.mainTableView!)
        self.mainTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(statusBarHeight+44)
            make.bottom.equalTo(self.bottomToolBarView!.snp.top)
        })
        self.mainTableView?.delegate = self
        self.mainTableView?.dataSource = self
        self.mainTableView?.separatorStyle = .none
        self.mainTableView?.register(JDSettlementTableViewCell.self, forCellReuseIdentifier: "myCell")
        self.mainTableView?.backgroundColor = self.commonColor
    }
    
    func setupBottomToolBarView() {
//        let tipsLabel = UILabel()
//        self.bottomToolBarView?.addSubview(tipsLabel)
//        tipsLabel.snp.makeConstraints { make in
//            make.left.right.top.equalTo(self.bottomToolBarView!)
//            make.height.equalTo(38)
//        }
//        tipsLabel.backgroundColor = color("#333333").withAlphaComponent(0.8)
//        tipsLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: .white, numberOfLines: 1)
//        tipsLabel.text = "5分钟后订单关闭，请尽快完成支付"
        
        let submitButton = UIButton(type: .custom)
        self.bottomToolBarView?.addSubview(submitButton)
        submitButton.snp.makeConstraints { make in
//            make.top.equalTo(tipsLabel.snp.bottom).offset(11)
            make.top.equalToSuperview().offset(11)
            make.size.equalTo(CGSizeMake(123, 48))
            make.right.equalTo(self.bottomToolBarView!).offset(-12)
        }
        submitButton.backgroundColor = color("#FA6161")
        submitButton.setTitle("结算", for: .normal)
        submitButton.setTitleColor(.white, for: .normal)
        submitButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
        submitButton.layer.cornerRadius = 24
        submitButton.addTarget(self, action: #selector(submitClick), for: .touchUpInside)
        
        let bottomTitleLabel = UILabel()
        self.bottomToolBarView?.addSubview(bottomTitleLabel)
        bottomTitleLabel.snp.makeConstraints { make in
            make.centerY.equalTo(submitButton)
            make.left.equalTo(self.bottomToolBarView!).offset(12)
        }
        bottomTitleLabel.text = "合计："
        bottomTitleLabel.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 16, weight: .regular), textColor: color("#333333"))
        
        self.settlementPriceLabel = UILabel()
        self.bottomToolBarView?.addSubview(self.settlementPriceLabel!)
        self.settlementPriceLabel?.snp.makeConstraints({ make in
            make.centerY.equalTo(submitButton)
            make.left.equalTo(bottomTitleLabel.snp.right).offset(2)
        })
        self.settlementPriceLabel?.text = "￥0.00"
        self.settlementPriceLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 20, weight: .semibold), textColor: color("#FA6161"))
        self.settlementPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
        
        
        self.settlementPriceLabel?.text = String.init(format: "￥%@", self.preOrderModel?.totalAmountText ?? "0.00")
        self.settlementPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
        
    }
    

    func createPreOrder() {
        var selectedGoodsList = [[String: Any]]()
                
        for speGoodsModel in self.selectedShopCartModel?.goodsList ?? [JDShopCartGoodsModel]() {
            
            if speGoodsModel.isSelected {
                var dic = [String: Any]()
                dic["goodsId"] = speGoodsModel.goodsId
                dic["goodsSkuId"] = speGoodsModel.goodsSkuId
                dic["goodsNum"] = speGoodsModel.count
                selectedGoodsList.append(dic)
            }
            
        }
        
        if selectedGoodsList.count <= 0 {
            self.view.toast(message: "请选择想要购买的商品")
            return;
        }
        
        var params = [String: Any]()
        params["goodsList"] = selectedGoodsList
        
        JDNetWorkRequest(.preSaveOrder(params)) { responseStr in
            
            printLog("预订单接口:\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {

                if let model = JDPreOrderModel.deserialize(from: responseStr, designatedPath: "data") {
                    self.preOrderModel = model
                    self.settlementPriceLabel?.text = String.init(format: "￥%@", model.totalAmountText ?? "0.00")
                    self.settlementPriceLabel?.priceString(UIFont.systemFont(ofSize: 12, weight: .regular), UIFont.systemFont(ofSize: 20, weight: .semibold))
                }
//                {"msg":"ok","data":{"postal":"116000","totalAmount":150000,"mobile":"13284231123","province":"辽宁省","totalFreightText":"8.00","receiverName":"朱","address":"华北路大湾市场","totalAmountText":"150.00","preOrderId":17,"totalTariffText":"14.00","defaultAddressId":2,"totalTariff":13500,"totalFreight":7500,"city":"大连市","district":"甘井子区"},"code":0}
            } else {
                self.view.toast(message: commonModel?.msg ?? "")
            }
            self.mainTableView?.reloadData()
        } failure: { error in
            
        } error: { errorCode in
            
        }
    }
    
    @objc func submitClick() {
        let paymentMethodView = JDPaymentMethodView()
        paymentMethodView.priceLabel?.text = self.settlementPriceLabel?.text
        paymentMethodView.priceLabel?.priceString(UIFont.systemFont(ofSize: 18, weight: .semibold), UIFont.systemFont(ofSize: 36, weight: .semibold))
        paymentMethodView.confirmButtonSelected = { [weak self] in
            // 认证完成之后的操作
//            self?.getNetData()
            
            self?.submitAction()
            paymentMethodView.removeFromSuperview()
        }
        JDTools.getKeyWindows()?.rootViewController?.view.addSubview(paymentMethodView)

    }
    
    /// 结算
    @objc func submitAction() {
        
        if self.currentCell?.buyerInfoModel == nil {
            self.view.toast(message: "请选择实名认证")
            return
        }

        printLog("开始结算")
        var params = [String: Any]()
        params["buyerName"] =  self.currentCell?.buyerInfoModel?.realName
//        "占位购买人姓名"//self.currentCell?.shopperNameInputView?.text
        params["buyerIdCardNumber"] = self.currentCell?.buyerInfoModel?.idCardNo
        //"占位，购买人身份证号"//self.currentCell?.shopperIDNumberInputView?.text
        params["userMessage"] = self.currentCell?.shopperMessageInputView?.text
        params["addressId"] = self.preOrderModel?.defaultAddressId
        params["preOrderId"] = self.preOrderModel?.preOrderId

        print("提交:\(params)")
        self.showLoading()
        JDNetWorkRequest(.saveOrder(params)) { responseStr in
            self.dismissLoading()
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
              
                // MARK: 进行假接口调整，模拟付款成功
                let dic = JSON(commonModel?.data as Any).dictionaryValue
                let orderId = JSON(dic["orderNo"] as Any).stringValue
                var payParams = [String: Any]()
                payParams["orderNo"] = orderId
                JDNetWorkRequest(.doOrderPay(payParams)) { responseStr in
                    print("这个参数:\(responseStr)")
                    let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
                    if commonModel?.code == "0" {
                        let alipayStr = JSON(commonModel?.data as Any).dictionaryValue["orderStr"]?.stringValue ?? ""
                        JDAlipayManager.pay(alipayStr)
                        DispatchQueue.main.asyncAfter(deadline: .now()+0.3) { [weak self] in
                            guard let weakSelf = self else { return  }
                            weakSelf.payingVC.payingClose = { [weak self] in
                                self?.navigationController?.popToRootViewController(animated: true)
                            }
                            weakSelf.payingVC.modalPresentationStyle = .overFullScreen
                            weakSelf.payingVC.modalTransitionStyle = .crossDissolve
                            weakSelf.present(weakSelf.payingVC, animated: true)
                        }
                    }
                } failure: { error in
                    print("付款错误:\(error)")
                } error: { errorCode in
                    print("付款异常code:\(errorCode)")
                }

//                JDDataNetWorkRequest(.doOrderPay(payParams)) { responseStr in
//                    
//                } failure: { error in
//                    print("付款错误:\(error)")
//                } error: { errorCode in
//                    print("付款异常code:\(errorCode)")
//                }
                
            } else {
                self.view.toast(message: commonModel?.msg ?? "网络异常")
            }
            printLog("开始结算啦:\(responseStr)")
            
//        开始结算啦:{"msg":"ok","code":0}
            
        } failure: { error in
            
            self.dismissLoading()
            self.view.toast(message: "网络异常")
            
        } error: { errorCode in
           
            self.dismissLoading()
            self.view.toast(message: "网络异常")
        }

    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDConfirmOrderViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as? JDSettlementTableViewCell
        
        self.currentCell = cell
        
        cell?.selectedShopCartModel = self.selectedShopCartModel
        cell?.preOrderModel = self.preOrderModel
        cell?.reloadData()
        
        if (self.shopperName?.count ?? 0) > 0 {
            cell?.shopperNameInputView?.text = self.shopperName ?? ""
        }
        if (self.shopperIDCard?.count ?? 0) > 0 {
            cell?.shopperIDNumberInputView?.text = self.shopperIDCard ?? ""
        }
        if (self.shopperMsg?.count ?? 0) > 0 {
            cell?.shopperMessageInputView?.text = self.shopperMsg
        }
        
        cell?.changeAddressButton?.addTarget(self, action: #selector(editAddressAction), for: .touchUpInside)
        
//        cell?.addAddressButton?.addTarget(self, action: #selector(editAddressAction), for: .touchUpInside)
        cell?.improveAddressButton?.addTarget(self, action: #selector(editAddressAction), for: .touchUpInside)
        cell?.changeAddressButton?.addTarget(self, action: #selector(editAddressAction), for: .touchUpInside)
        
        
        cell?.changeBuyerInfoButton?.addTarget(self, action: #selector(changeBuyerInfoAction), for: .touchUpInside)
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        return 1000
        return UITableView.automaticDimension
    }
    
}

extension JDConfirmOrderViewController {
    
    @objc func changeBuyerInfoAction() {
        print("选择实名认证")
        let authenticationListVC = JDAuthenticationListViewController()
        authenticationListVC.isFromShopcar = true
        authenticationListVC.selectedAuthenticationInfoCompeletd = {[weak self] currentModel in
            self?.currentCell?.buyerInfoModel = currentModel
            
//            self?.currentCell?.reloadData()
            self?.mainTableView?.reloadData()
            printLog("这里要怎么赋值啊")
            
        }
        self.hidesBottomBarPushViewController(authenticationListVC)
        
    }
    
    @objc func editAddressAction() {
        
        let editAddressVC = JDAddressListViewController()
        editAddressVC.isSelectedAddress = true
        editAddressVC.changeReceiveAddress = {[weak self] addressModel in
            
            self?.preOrderModel?.defaultAddressId = addressModel.id
            self?.preOrderModel?.receiverName = addressModel.receiverName
            self?.preOrderModel?.mobile = addressModel.mobile
            self?.preOrderModel?.province = addressModel.province
            self?.preOrderModel?.city = addressModel.city
            self?.preOrderModel?.district = addressModel.district
            self?.preOrderModel?.address = addressModel.address
            
            
//            self?.shopperName = self?.currentCell?.shopperNameInputView?.text
//            self?.shopperIDCard = self?.currentCell?.shopperIDNumberInputView?.text
//            self?.shopperMsg = self?.currentCell?.shopperMessageInputView?.text
            self?.currentCell?.reloadData()
            
            self?.mainTableView?.reloadData()
        }
        self.hidesBottomBarPushViewController(editAddressVC)
    }
}
